<template>
    <div>
        <el-row>
            <!-- 信息查询 -->
            <el-form size="mini" inline ref="queryFormRef" :model="queryForm">
                <el-form-item label="小区名称" prop="plotName">
                    <el-input v-model="queryForm.plotName"></el-input>
                </el-form-item>
                <el-form-item label="小区编码" prop="plotNo">
                    <el-input v-model="queryForm.plotNo"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="resetForm('queryForm'), getListPlot()">重置</el-button>
                    <el-button type="primary" plain @click="handleAdd">添加</el-button>
                </el-form-item>
            </el-form>

            <!-- 表格 -->
            <el-table :data="plotList">
                <el-table-column type="index" label="序号" align="center" width="50"
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="plotName" label="小区名字" align="center" width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="city" label="城市" align="center" width="250"></el-table-column>
                <el-table-column prop="plotNo" label="小区编码" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="cityDtl" label="小区地址" align="center" width="200"
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" width="200"
                    show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" align="center" width="280" show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-row type="flex" justify="space-between">

                            <el-button type="success" @click="getDtlPlot(row.plotId)"
                                v-show="curId !== row.plotId">切换小区</el-button>
                            <div v-show="curId === row.plotId" style="padding: 0 49px;"></div>
                            <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-row type="flex">

                <!-- .sync类似v-model，实现页面数据双向响应式 -->
                <el-pagination background @current-change="handleChange" :current-page.sync="pageIniation.pageNum"
                    :page-sizes="[5, 10, 15, 20]" :page-size="pageIniation.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="pageIniation.total"
                    @size-change="handleChangeSize">
                </el-pagination>


            </el-row>

            <!-- 弹窗：实现添加和编辑 -->
            <el-dialog :visible.sync="dialog.visible" width="700px" @close="resetForm('dialogForm')" class="elDialog">
                <!-- 标题 -->
                <template #title>
                    <div style="text-align: center;">
                        {{ dialog.mode === "add" ? "添加小区" : "编辑小区" }}
                    </div>
                </template>

                <el-form :model="dialog.form" label-width="70px" size="small" :rules="dialog.rules" ref="dialogFormRef"
                    hide-required-asterisk>
                    <el-form-item label="小区名字" prop="plotName">
                        <el-input v-model="dialog.form.plotName">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="小区地址" prop="cityDtl">
                        <el-input v-model="dialog.form.cityDtl">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="小区地区" prop="city">
                        <!-- 级联选择器 -->

                        <el-row type="flex" justify="space-between">
                            <el-select v-model="dialog.form.provId" @change="handleChangeProvince" placeholder="请选择省份">
                                <el-option v-for="province in provList" :label="province.provName"
                                    :key="province.provId" :value="province.provId"></el-option>
                            </el-select>

                            <el-select v-model="dialog.form.cityId" @change="handleChangeCity" placeholder="请选择城市">
                                <el-option v-for="city in cityList" :label="city.cityName" :key="city.cityId"
                                    :value="city.cityId"></el-option>
                            </el-select>

                            <el-select v-model="dialog.form.areaId" @change="handleChangeArea" placeholder="请选择区县">
                                <el-option v-for="area in areaList" :label="area.areaName" :key="area.areaId"
                                    :value="area.areaId"></el-option>
                            </el-select>

                        </el-row>


                    </el-form-item>
                    <el-form-item align="right">
                        <el-button type="plain" @click="dialog.visible = false,
                            resetForm('dialogForm')">取消</el-button>
                        <el-button type="primary" @click="handleSubmit">确定</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-row>
    </div>
</template>

<script>
import { query } from '@/utils/common.js';
import { listPlot, listArea, addPlot, editPlot, deletePlot } from '@/api/info.js';
export default {
    name: "Info",
    data() {
        return {
            //小区信息列表
            plotList: [],

            //信息查询
            queryForm: {
                plotName: undefined,
                plotNo: undefined
            },

            //分页
            pageIniation: {
                pageNum: 1,
                pageSize: 5,
                total: 0,
            },

            curId: undefined,

            //弹窗
            dialog: {
                mode: "add",//添加标志
                visible: false,
                //小区名字和地址
                form: {
                    city: undefined,
                    cityDtl: "",
                    coordinate: undefined,
                    plotName: undefined,

                    //省市区id
                    provId: undefined,
                    cityId: undefined,
                    areaId: undefined
                },

                //校验
                rules: {
                    plotName: [{ required: true, message: "请输入小区名字", trigger: "blur" }],
                    cityDtl: [{ required: true, message: "请输入小区地址", trigger: ["blur", "change"] }],
                }
            },

            //省市区数据
            provList: [],
            cityList: [],
            areaList: [],

            //省市区名字
            provName: undefined,
            cityName: undefined,
            areaName: undefined

        }



    },
    computed: {

    },

    created() {
        //小区ID
        this.curId = this.$store.state.curId || undefined,
            this.getListPlot()
        this.getListArea()

        if (this.curId) {
            this.getDtlPlot(this.curId)
        }

    },
    methods: {
        //获取小区信息列表
        getListPlot(query = {}) {
            //过滤掉多余的参数
            const { total, ...rest } = this.pageIniation
            listPlot({ ...query, ...rest }).then(res => {
                console.log(res);
                this.plotList = res.rows
                this.pageIniation.total = res.total

            }).catch(err => {
            })
        },

        //点击查询，获取小区信息
        handleQuery() {
            //查询为空(包括空格)时，进行提示，提示先输入值，至少有一个输入框有值：some,用于数组
            const hasInput = query(this.queryForm)
            //符合条件，至少有一项符合
            this.pageIniation.pageNum = 1
            if (hasInput) return this.getListPlot(this.queryForm)

            //不符合，进行提示
            this.$message.warning("请输入值！")

        },

        //查询后重置
        resetForm(refName) {
            this.$refs[`${refName}Ref`].resetFields()

        },

        handleChange(value) {
            //更新当前页
            this.pageIniation.pageNum = value
            this.getListPlot(this.queryForm)
        },

        handleChangeSize(value) {
            //更新当前页
            this.pageIniation.pageSize = value
            this.getListPlot(this.queryForm)
        },

        //添加
        handleAdd() {
            this.dialog.visible = true
            this.dialog.mode = "add"

            //实现点击编辑之后再点击添加，数据清空
            // this.dialog.form = {
            //     city: undefined,
            //     cityDtl: "",
            //     coordinate: undefined,
            //     plotName: undefined,

            //     provId: undefined,
            //     cityId: undefined,
            //     areaId: undefined

            // },

            // this.provName = undefined,
            // this.cityName = undefined,
            // this.areaName = undefined

            this.dialog.form = {
                city: undefined,
                cityDtl: "",
                coordinate: undefined,
                plotName: undefined,
                provId: undefined,
                cityId: undefined,
                areaId: undefined
            }

            // 清空省市区列表
            this.cityList = [];
            this.areaList = [];

            // 清空省市区名称
            this.provName = undefined;
            this.cityName = undefined;
            this.areaName = undefined;

        },




        //获取小区省市区信息
        getListArea() {
            listArea().then(res => {
                console.log(res);
                this.provList = res.data

            })

        },


        //点击省份后确定城市
        handleChangeProvince(proVal) {
            this.dialog.form.cityId = undefined
            const { provName, cityAreaVos } = this.provList.find(prov => prov.provId === proVal) || {}
            this.provName = provName
            this.cityList = cityAreaVos
        },

        //再点击城市后确定区县
        handleChangeCity(cityVal) {
            this.dialog.form.areaId = undefined
            const { cityName, areaVos } = this.cityList.find(city => city.cityId === cityVal) || {}
            this.cityName = cityName
            this.areaList = areaVos

        },

        handleChangeArea(areaVal) {
            const { areaName } = this.areaList.find(area => area.areaId === areaVal) || {}
            this.areaName = areaName

        },


        //切换小区（根据id）
        getDtlPlot(id) {

            this.curId = id
            this.$store.commit("setCurId", id)
            this.$store.dispatch("getPlotData", this.curId)
        },

        //提交
        handleSubmit() {

            this.$refs[`dialogFormRef`].validate(async valid => {

                //空值提交先进行校验提醒 ,检验失败
                if (!valid) return


                let { provId, cityId, areaId, coordinate } = this.dialog.form
                coordinate = [provId, cityId, areaId].join(",")
                let city = [this.provName, this.cityName, this.areaName].join("")

                //过滤不需要的参数,这个方法会出现实现添加时小区id一直为空的问题
                // let { createTime, plotId, plotNo, ...rest } = this.dialog.form
                // let result = {}

                // const submitData = {
                //     ...rest,
                //     city,
                //     coordinate
                // }


                // switch (this.dialog.mode) {
                //     case "add":
                //         try {
                //             result = await addPlot(submitData)
                //         } catch (error) {
                //             break;
                //         }

                //     case "edit":
                //         try {
                //             result = await editPlot({ ...submitData, plotId })
                //         } catch (error) {
                //             break;
                //         }

                // }



                // //提示添加成功
                // this.$message.success(result.msg)
                // //更新小区信息
                // this.getListPlot()
                // //关闭弹窗
                // this.dialog.visible = false
                // //添加后重置表单
                // this.resetForm("dialogForm")//this.resetForm(dialog.Form)

                // 创建提交数据的副本，避免修改原始数据
                const formData = { ...this.dialog.form };

                // 移除不需要的字段
                delete formData.createTime;
                delete formData.plotNo;

                // 在添加模式下明确移除 plotId
                if (this.dialog.mode === "add") {
                    delete formData.plotId;
                }

                const submitData = {
                    ...formData,
                    city,
                    coordinate
                };


                let result = {};
                try {
                    if (this.dialog.mode === "add") {
                        result = await addPlot(submitData);
                    } else if (this.dialog.mode === "edit") {
                        result = await editPlot(submitData);
                    }

                    this.$message.success(result.msg);
                    this.getListPlot();
                    this.dialog.visible = false;
                    this.resetForm("dialogForm");

                } catch (error) {
                    console.error('提交失败:', error);
                    this.$message.error('操作失败，请重试');
                }

            })


        },

        //编辑
        handleEdit(row) {
            this.dialog.visible = true
            this.dialog.mode = "edit"

            //数据回显
            this.$nextTick(() => {
                this.dialog.form = JSON.parse(JSON.stringify(row))

                //将字符串的Id转为数字
                const [provId, cityId, areaId] = this.dialog.form.coordinate.split(",").map(item => Number(item))

                this.dialog.form = {
                    ...this.dialog.form,
                    provId, cityId, areaId
                }

                this.cityList = this.provList.find(prov => prov.provId === provId).cityAreaVos
                this.areaList = this.cityList.find(city => city.cityId === cityId).areaVos
            })

        },

        //删除小区
        handleDelete(row) {
            //提示
            this.$confirm(`是否删除【${row.plotName}】小区？`, "系统提示", {
                type: "warning",
                //确定.then
            }).then(() => {
                deletePlot(row.plotId).then(res => {
                    this.$message.success(res.msg)
                    //删除后，重新更新小区信息
                    this.getListPlot()
                })
                //取消.catch
            }).catch((err) => { })
        }

    },


}


</script>

<style lang="scss" scoped>
.elDialog {
    .el-form {
        .el-form-item {
            ::v-deep(.el-input__inner) {
                width: 160px
            }
        }
    }
}
</style>